package com.cloudbroker.bcs.platform.ltb.middle.util.websocket;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 系统通知websocket
 * 
 * @author shenmy14613
 *
 */
@ServerEndpoint(value = "/rollNoticeSocket/{customer_id}")
public class RollNoticeSocket {
	private static final Logger logger = LoggerFactory
			.getLogger(RollNoticeSocket.class);
	static Map<String, Session> sessionMap = new ConcurrentHashMap<String, Session>();

	@OnOpen
	public void onOpen(Session session,
			@PathParam(value = "customer_id") String customer_id) {
		sessionMap.put(customer_id, session);
	}

	@OnMessage
	public void onMessage(String unscrambledWord, Session session) {
		broadcastAll(unscrambledWord);
	}

	/**
	 * 广播给所有人
	 * 
	 * @param message
	 */
	public static void broadcastAll(String message) {
		Set<Map.Entry<String, Session>> set = sessionMap.entrySet();
		for (Map.Entry<String, Session> i : set) {
			try {
				i.getValue().getBasicRemote().sendText(message);
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
		}
	}

	/**
	 * 发送给一个人
	 * 
	 * @param customerId
	 * @param message
	 */
	public static void broadcastOne(String customerId, String message) {
		Session session = sessionMap.get(customerId);
		if (session != null) {
			try {
				session.getBasicRemote().sendText(message);
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}
	}

	public static void broadcastUserList(List<String> customerIds,
			String message) {
		for (String customerId : customerIds) {
			broadcastOne(customerId, message);
		}
	}

	@OnClose
	public void onClose(Session session, CloseReason closeReason,
			@PathParam(value = "customer_id") String customer_id) {
		sessionMap.remove(customer_id);
		logger.error(closeReason.getReasonPhrase());
	}

	@OnError
	public void error(Session session, Throwable throwable,
			@PathParam(value = "customer_id") String customer_id) {
		sessionMap.remove(customer_id);
		logger.error(throwable.getMessage());
	}
}
